import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '@/views/Home.vue';
import Register from '@/views/Register/index.vue';
import StepOne from '@/views/Register/StepOne.vue';
import StepTwo from '@/views/Register/StepTwo.vue';
import StepThree from '@/views/Register/StepThree.vue';
import Address from '@/views/Address.vue';
import Login from '@/views/Login.vue';
import Cart from '@/views/Cart.vue';
import City from '@/views/City.vue';
import Detail from '@/views/Detail.vue';
import NotFound from '@/views/NotFound.vue';
import Search from '@/views/Search.vue';
import Order from '@/views/Order.vue';
import User from '@/views/User.vue';

const routes = [
    { path: '/', component: Home },
    {
        path: '/register',
        component: Register,
        children: [
            { path: 'stepone', component: StepOne },
            { path: 'steptwo', component: StepTwo },
            { path: 'stepthree', component: StepThree },
        ]
    },
    {
        path: '/address',
        component: Address,
        meta: {
            needCheckLogin: true
        }
    },
    { path: '/login', component: Login },
    {
        path: '/cart',
        component: Cart,
        meta: {
            needCheckLogin: true
        }
    },
    { path: '/city', component: City },
    { path: '/detail/:id', component: Detail },
    { path: '/search', component: Search },
    {
        path: '/order',
        component: Order,
        meta: {
            needCheckLogin: true
        }
    },
    {
        path: '/user',
        component: User,
        meta: {
            needCheckLogin: true
        }
    },
    {path:'/:pathMatch(.*)*',component:NotFound}

]

const router = createRouter({
    history: createWebHashHistory(),
    routes:routes as any
})

//全局路由守卫
router.beforeEach(to => {
    // to:去到的路由信息对象
    if (to.meta.needCheckLogin) {
        // console.log('需要检查登录状态');
        if (localStorage.getItem('token') && localStorage.getItem('userid')) {
            return true;
        } else {
            router.push('/login')
            return false;
        }
    } else {
        // console.log("不需要检查登录状态");
        return true;
    }
})

export default router